package com.example.spring.test;

import org.junit.Before;
import org.junit.Test;

import java.util.Calendar;

public class CalendarDemo {

    Calendar calendar = null;

    @Before
    public void test() {
        calendar = Calendar.getInstance();
    }

    //获取年月日时分秒星期
    @Test
    public void test1() {
        int year = calendar.get(Calendar.YEAR);// 获取年

        int month = calendar.get(Calendar.MONTH) + 1;// 获取月，这里需要需要月份的范围为0~11，因此获取月份的时候需要+1才是当前月份值

        int day = calendar.get(Calendar.DAY_OF_MONTH);// 24小时表示

//        int hour = calendar.get(Calendar.HOUR);// 获取时
        int hour = calendar.get(Calendar.HOUR_OF_DAY); // 24小时表示

        int minute = calendar.get(Calendar.MINUTE);// 获取分

        int second = calendar.get(Calendar.SECOND);// 获取秒

        int weekday = calendar.get(Calendar.DAY_OF_WEEK);

        System.out.println(year + "年" + month + "月" + day + "日" + hour + "时" + minute + "分" + second + "秒" + "星期" + weekday);
    }

    //一年后的今天
    @Test
    public void test2() {
        // 同理换成下个月的今天calendar.add(Calendar.MONTH, 1);
        calendar.add(Calendar.YEAR, 1);

        int year = calendar.get(Calendar.YEAR);

        int month = calendar.get(Calendar.MONTH) + 1;

        int day = calendar.get(Calendar.DAY_OF_MONTH);

        System.out.println("一年后的今天：" + year + "年" + month + "月" + day + "日");
    }

    //获取任意一个月的最后一天
    @Test
    public void Test3(){
        int currentMonth = 6;// 假设求6月的最后一天

        // 先求出7月份的第一天，实际中这里6为外部传递进来的currentMonth变量
        calendar.set(calendar.get(Calendar.YEAR), currentMonth, 1);

        calendar.add(Calendar.DATE, -1);

        int day = calendar.get(Calendar.DAY_OF_MONTH);

        System.out.println("6月份的最后一天为" + day + "号");
    }

    // 设置日期
    @Test
    public void Test4(){
        calendar.set(Calendar.YEAR, 2000);
        System.out.println("现在是" + calendar.get(Calendar.YEAR) + "年");

        calendar.set(2008, 8, 8);

        int year = calendar.get(Calendar.YEAR);

        int month = calendar.get(Calendar.MONTH);

        int day = calendar.get(Calendar.DAY_OF_MONTH);

        System.out.println("现在是" + year + "年" + month + "月" + day + "日");
    }


}
